package com.demo.listener;

import com.demo.event.MyUserEvent;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.boot.context.event.ApplicationStartingEvent;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.GenericApplicationListener;
import org.springframework.core.ResolvableType;

/**
 * 通过实现GenericApplicationListener接口从而选择性的订阅多个事件
 */
public class MyGenericApplicationListener implements GenericApplicationListener {
    private static final Class<?>[] EVENT_TYPES = { ApplicationStartingEvent.class,
            ApplicationEnvironmentPreparedEvent.class,MyUserEvent.class};

    /**
     * 用于判断是否时自己支持的事件类型
     * @param eventType
     * @return
     */
    @Override
    public boolean supportsEventType(ResolvableType eventType) {
        for (Class<?> supportedType : EVENT_TYPES) {
            if (supportedType.isAssignableFrom(eventType.getRawClass())) {
                return true;
            }
        }
        return false;
    }


    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if (event instanceof ApplicationEnvironmentPreparedEvent) {
            onApplicationEnvironmentPreparedEvent((ApplicationEnvironmentPreparedEvent)event);
        } else if (event instanceof ApplicationStartingEvent) {
            onApplicationStartingEvent((ApplicationStartingEvent) event);
        } else if (event instanceof MyUserEvent) {
            testEventMethod((MyUserEvent) event);
        }


    }

    public void onApplicationEnvironmentPreparedEvent(ApplicationEnvironmentPreparedEvent event) {
        System.out.println("---------------- this is MyGenericApplicationListener onApplicationEnvironmentPreparedEvent");
    }

    public void onApplicationStartingEvent(ApplicationStartingEvent startingEvent) {
        System.out.println("---------------- this is MyGenericApplicationListener onApplicationStartingEvent");
    }

    public void testEventMethod(MyUserEvent e){
        System.out.println("---------------- this is MyGenericApplicationListener MyUserEvent");
    }

}
